/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package db

import (
	"fmt"
	"os"
	"time"

	"xorm.io/core"

	"github.com/go-xorm/xorm"
	_ "github.com/lib/pq"

	"icep/common/logger"
	"icep/config"
)

var log = logger.GetLogger("database")

type PostgresConfig struct {
	Host     string
	Port     int
	User     string
	Password string
	DBName   string
	Showsql  bool
	Maxidle  int
	Maxopen  int
}

func loadConfig() *PostgresConfig {
	dbConfig := &PostgresConfig{}
	dbConfig.Host = config.Get("icep.db.host", "localhost")
	dbConfig.Port = config.GetInt("icep.db.port", 5432)
	dbConfig.User = config.Get("icep.db.user", "postgres")
	dbConfig.Password = config.Get("icep.db.password", "")
	dbConfig.DBName = config.Get("icep.db.database", "icep")
	dbConfig.Showsql = config.GetBool("icep.db.showsql")
	dbConfig.Maxidle = config.GetInt("icep.db.max-idle", 100)
	dbConfig.Maxopen = config.GetInt("icep.db.max-open", 10)

	return dbConfig
}

func GetEngine() *xorm.Engine {
	pgConfig := loadConfig()
	pgInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		pgConfig.Host, pgConfig.Port, pgConfig.User, pgConfig.Password, pgConfig.DBName)
	engine, err := xorm.NewEngine("postgres", pgInfo)
	if err != nil {
		log.Errorf("get engine error: %v", err)
		return nil
	}

	// 打印sql
	loga := xorm.NewSimpleLogger(os.Stdout)
	switch os.Getenv("ICEP_LOG_LEVEL") {
	case "INFO":
		loga.SetLevel(core.LOG_INFO)
		break
	case "DEBUG":
		loga.SetLevel(core.LOG_DEBUG)
		break
	case "WARNING":
		loga.SetLevel(core.LOG_WARNING)
		break
	case "ERROR":
		loga.SetLevel(core.LOG_ERR)
		break
	default:
		loga.SetLevel(core.LOG_INFO)
	}

	engine.SetLogger(loga)
	engine.ShowSQL(pgConfig.Showsql)
	engine.SetMaxIdleConns(pgConfig.Maxidle)
	engine.SetMaxOpenConns(pgConfig.Maxopen)
	//连接生存时间半个小时
	engine.SetConnMaxLifetime(1800 * time.Second)
	return engine
}
